const fs = require("node:fs");
const path = require("node:path");

const itemMapper = require("../mapper/itemMapper.js");

function add(entity) {
    return new Promise((resolve, reject) => { 
        if (!entity.pId || !entity.name) {
            reject("parameter error")
            return;
        }
       
        itemMapper.addItem(entity, function(err){
            if (err) { reject(err); return; }
            resolve(this.lastID)
        })
    })  
}
exports.add = add

function get(entityId) {
    return new Promise((resolve, reject) => {
        itemMapper.selectItemById(entityId, (err, entity) => {
            if (err != null) { reject(err); return; }
            resolve(entity);
        })
    })
}
exports.get = get

function getAll() {
    return new Promise((resolve, reject) => {
        itemMapper.selectAllItem((err, entities) => {
            if (err != null) { reject(err); return; }
            resolve(entities);
        })
    })
}
exports.getAll = getAll

function deleteEntity(entityId) {
    return new Promise((resolve, reject) => {
        if (!entityId) {
            reject("parameter error")
            return;
        }
        
        itemMapper.deleteItemById(entityId, (err) => {
            if (err) { reject(err); return; }
        })
        resolve()
    })
}
exports.delete = deleteEntity

function update(entity) {
    return new Promise((resolve, reject) => { 
        if (!entity.id || !entity.name) {
            reject("parameter error")
            return;
        }
        
        itemMapper.updateItem(entity, (err) => {
            if (err) { reject(err); return; }
            resolve()
        })
    })  
}
exports.update = update

function updateAll(entities) {
    return new Promise((resolve, reject) => { 
        if (!Array.isArray(entities)) {
            reject("parameter error")
            return;
        }
        
        itemMapper.updateItems(entities, err => {
            if (err) { reject(err); return; }
            resolve()
        })
    })  
}
exports.updateAll = updateAll

function saveAllItems() {
    return new Promise((resolve, reject) => {
        itemMapper.selectAllItem((err, rows) => {
            if (err) { reject(err); return; }
    
            var writer = fs.createWriteStream(path.join(__dirname, "../../core/static/js2/item.js"));
            writer.write("var _items = ");
            writer.write(JSON.stringify(rows));
            writer.end(';');
    
            resolve();
        })
    })
}
exports.saveAllItems = saveAllItems

